package com.xagcdx.group1.web;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.xagcdx.group1.bean.Depart;
import com.xagcdx.group1.bean.Job;
import com.xagcdx.group1.bean.Staff;
import com.xagcdx.group1.bean.StaffChange;
import com.xagcdx.group1.bean.Summit;
import com.xagcdx.group1.bean.User;
import com.xagcdx.group1.service.DepartService;
import com.xagcdx.group1.service.StaffChangeService;
import com.xagcdx.group1.service.StaffService;
import com.xagcdx.group1.service.SummitService;
import com.xagcdx.group1.service.UserService;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author grou1
 * @since 2020-06-09
 */
@RestController
@RequestMapping("/staff")
public class StaffController {
	@Autowired
	private UserService userService;
	@Autowired
	private DepartService departService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private SummitService summitService;
	@Autowired
	private StaffChangeService staffChangeService;
	@RequestMapping("/listPage")
	public String listPage(Integer page, Integer limit, String scode,String staffstatu, String summitstatu, String edittime) {
		Map<String, Object> result = new HashMap<String, Object>(10);
		result.put("count", staffService.counts(scode, staffstatu, summitstatu, edittime));
		result.put("msg", "");
		result.put("code", 0);
		result.put("data", staffService.staffListPage((page - 1) * limit, limit, scode, staffstatu, summitstatu, edittime));
		return new Gson().toJson(result);
	}
	@RequestMapping("/add")
	public String add(Staff staff) {
		Subject subject= SecurityUtils.getSubject();
        Session session=subject.getSession();
        User user = (User) session.getAttribute("user");
        staff.setEditname(user.getUname());
        //获取时间
        long d=System.currentTimeMillis();
        Date date = new Date(d);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String finaldate = dateFormat.format(date);
        staff.setEdittime(finaldate);
        //设定编码
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("did", staff.getDid());
		Depart depart = departService.getOne(queryWrapper);
		QueryWrapper<Staff> queryWrapper2 = new QueryWrapper<Staff>();
		queryWrapper2.like("scode", "%"+depart.getDdesc()+"%");
		Integer maxcount = staffService.count(queryWrapper2);
		String scodeString = depart.getDdesc()+String.format("%4d", maxcount+1).replace(" ", "0");
		staff.setScode(scodeString);
		//保存staff
		boolean save = staffService.save(staff);
		if(save) {
			
			//保存staffchange
			queryWrapper2.eq("scode", scodeString);
			Staff staff2 = staffService.getOne(queryWrapper2);
			System.out.println(staff2);
			String sidString = staff2.getSid();
			//staffchange信息保存
			StaffChange staffChange = new StaffChange();
			staffChange.setSid(staff2.getSid());
			staffChange.setDid(staff2.getDid());
			staffChange.setJid(staff2.getJid());
			staffChange.setJtid(staff2.getJtid());
			staffChange.setScode(staff2.getScode());
			staffChange.setName(staff2.getName());
			staffChange.setSex(staff2.getSex());
			staffChange.setEmail(staff2.getEmail());
			staffChange.setTelenum(staff2.getTelenum());
			staffChange.setPlace(staff2.getPlace());
			staffChange.setSnum(staff2.getSnum());
			staffChange.setBplace(staff2.getBplace());
			staffChange.setPolitictype(staff2.getPolitictype());
			staffChange.setScardnum(staff2.getScardnum());
			staffChange.setGradschool(staff2.getGradschool());
			staffChange.setDegree(staff2.getDegree());
			staffChange.setMajor(staff2.getMajor());
			staffChange.setSalarytype(staff2.getSalarytype());
			staffChange.setBank(staff2.getBank());
			staffChange.setBcardnum(staff2.getBcardnum());
			staffChange.setEditname(staff2.getEditname());
			staffChange.setEdittime(staff2.getEdittime());
			staffChange.setSelfexperience(staff2.getSelfexperience());
			staffChange.setFamilyinfo(staff2.getFamilyinfo());
			staffChange.setStaffdesc(staff2.getStaffdesc());
			staffChange.setStaffstatu(staff2.getStaffstatu());
			staffChange.setImage(staff2.getImage());
			staffChange.setResume(staff2.getResume());
			System.out.println(staffChange);
			boolean save2 = staffChangeService.save(staffChange);
			//保存summit表
			if(save2) {
				QueryWrapper<StaffChange> queryWrapper3 = new QueryWrapper<StaffChange>();
				queryWrapper3.eq("sid", sidString);
				StaffChange staffChange2 = staffChangeService.getOne(queryWrapper3);
				Summit summit = new Summit();
				summit.setSid(staffChange2.getSid());
				summit.setScid(staffChange2.getScid());
				Summit summit2 = staff.getSummit();
				summit.setSummitstatu("1");
				summit.setSummittype("5");
				summit.setZid(user.getUname());
				summit.setSubmittime(finaldate);
				boolean save3 = summitService.save(summit);
				if(save3) {
					return "1";
				} else {
					return "0";
				}
				
			}else {
				return "0";
			}
		}else {
			return "0";
		}
	}
	@RequestMapping("/pass")
	public String pass(Staff staff) {
		QueryWrapper<Staff> queryWrapper = new QueryWrapper<Staff>();
		queryWrapper.eq("sid", staff.getSid());
		Staff realStaff =  staffService.getOne(queryWrapper);
		QueryWrapper<Summit> queryWrapper2 = new QueryWrapper<Summit>();
		queryWrapper2.eq("sid", staff.getSid());
		Summit realSummit = summitService.getOne(queryWrapper2);
		
		//获取变更类型，分别更新
		String summittype= realSummit.getSummittype();
		if("0".equals(summittype)) {
			//转正
			realStaff.setStaffstatu(staff.getStaffstatu());
		}else if("1".equals(summittype)) {
			//调薪
			realStaff.setSalarytype(staff.getSalarytype());
		}else if("2".equals(summittype)) {
			//调职
			QueryWrapper<StaffChange> queryWrapper3 = new QueryWrapper<StaffChange>();
			queryWrapper3.eq("sid", staff.getSid());
			StaffChange staffChange = staffChangeService.getOne(queryWrapper3);
			realStaff.setDid(staffChange.getDid());
			realStaff.setJid(staffChange.getJid());
			realStaff.setJtid(staffChange.getJtid());
		}else if("3".equals(summittype)) {
			//离职
			realStaff.setStaffstatu(staff.getStaffstatu());
		}else if("4".equals(summittype)) {
			//删除
			realStaff.setStaffstatu(staff.getStaffstatu());
		}else if("5".equals(summittype)) {
			//档案新增，只需要将staff所有信息加上部门职位职称信息即可
			staff.setDid(realStaff.getDid());
			staff.setJid(realStaff.getJid());
			staff.setJtid(realStaff.getJtid());
		}else if("6".equals(summittype)) {
			//修改信息
			staff.setDid(realStaff.getDid());
			staff.setJid(realStaff.getJid());
			staff.setJtid(realStaff.getJtid());
		}
		//更新staff表
		if("5".equals(summittype) || "6".equals(summittype)) {
			boolean save1 = staffService.update(staff,queryWrapper);
			if(save1) {
				realSummit.setSummitstatu("2");
				//审核人id
				Subject subject= SecurityUtils.getSubject();
		        Session session=subject.getSession();
		        User user = (User) session.getAttribute("user");
				realSummit.setApplyid(user.getUname());
				//审核人时间
				long d=System.currentTimeMillis();
		        Date date = new Date(d);
		        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		        String finaldate = dateFormat.format(date);
		        realSummit.setApplytime(finaldate);
		        //更新summit
				boolean save2 = summitService.update(realSummit,queryWrapper2);
				if(save2) {
					return "1";
				}else {
					return "0";
				}
			}else {
				return "0";
			}
		}else {
			boolean save1 = staffService.update(realStaff,queryWrapper);
			if(save1) {
				realSummit.setSummitstatu("2");
				boolean save2 = summitService.update(realSummit,queryWrapper2);
				if(save2) {
					return "1";
				}else {
					return "0";
				}
			}else {
				return "0";
			}
		}
		
	}
	@RequestMapping("/refuse")
	public String refuse(Staff staff) {
		QueryWrapper<Summit> queryWrapper = new QueryWrapper<Summit>();
		queryWrapper.eq("sid", staff.getSid());
		Summit realSummit = summitService.getOne(queryWrapper);
		//审核人id
		Subject subject= SecurityUtils.getSubject();
        Session session=subject.getSession();
        User user = (User) session.getAttribute("user");
		realSummit.setApplyid(user.getUname());
		//审核时间
		long d=System.currentTimeMillis();
        Date date = new Date(d);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String finaldate = dateFormat.format(date);
        realSummit.setApplytime(finaldate);
        //审核状态
        realSummit.setSummitstatu("3");
        boolean save = summitService.update(realSummit,queryWrapper);
		if(save) {
			return "1";
		}else {
			return "0";
		}

	}
	@RequestMapping("/del")
	public String del(String sid) {
		System.out.println(sid);
		QueryWrapper<StaffChange> queryWrapper = new QueryWrapper<StaffChange>();
		queryWrapper.eq("sid", sid);
		StaffChange staffChange = staffChangeService.getOne(queryWrapper);
		staffChange.setStaffstatu("4");
		boolean save = staffChangeService.update(staffChange,queryWrapper);
		QueryWrapper<Summit> queryWrapper2 = new QueryWrapper<Summit>();
		queryWrapper2.eq("sid",sid);
		Summit summit = summitService.getOne(queryWrapper2);
		summit.setSummittype("4");
		summit.setSummitstatu("1");
		boolean save2 = summitService.update(summit,queryWrapper2);
		if(save) {
			if(save2) {
				return "1";
			}else {
				return "0";
			}
		}else {
			return "0";
		}
	}
	@RequestMapping(value = "/upload/headImg", method = {RequestMethod.POST})
	@ResponseBody
	public Object headImg(@RequestParam(value="file",required=false) MultipartFile file,String sid, HttpServletRequest request, HttpServletResponse response) throws Exception {
	    if (SecurityUtils.getSubject().isAuthenticated() == false) {
	        return "0";
	    }
	    
	    String prefix="";
	    String dateStr="";
	    //淇濆瓨涓婁紶
	     OutputStream out = null;
	    InputStream fileInput=null;
	    String uploadDir="//";
		try{
	        if(file!=null){
	            String originalName = file.getOriginalFilename();
	            prefix=originalName.substring(originalName.lastIndexOf(".")+1);
	            dateStr = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss SSS").format(new Date());
	            String filepath = request.getServletContext().getRealPath("photohead") + uploadDir + sid + "." + prefix;
	            filepath = filepath.replace("\\", "/");
	            File files=new File(filepath);
	            //鎵撳嵃鏌ョ湅涓婁紶璺緞
	           QueryWrapper<Staff> queryWrapper = new QueryWrapper<Staff>();
	           queryWrapper.eq("sid", sid);
	           Staff staff =  staffService.getOne(queryWrapper);
	           staff.setImage("/photohead"+ uploadDir + sid + "." + prefix);
	           boolean save = staffService.updateById(staff);
	       
	            
	            if(!files.getParentFile().exists()){
	                files.getParentFile().mkdirs();
	            }
	            file.transferTo(files);
	        }
	    }catch (Exception e){
	    }finally{
	        try {
	            if(out!=null){
	                out.close();
	            }
	            if(fileInput!=null){
	                fileInput.close();
	            }
	        } catch (IOException e) {
	        }
	    }
	    Map<String,Object> map2=new HashMap<>();
	    Map<String,Object> map=new HashMap<>();
	    map.put("code",0);
	    map.put("msg","");
	    map.put("data",map2);
	    map2.put("src","../../../static"+uploadDir + dateStr + "." + prefix);
	    return map;
	}
	@RequestMapping("/getinfo")
	public String getinfo(String sid) {
		QueryWrapper<Staff> queryWrapper = new QueryWrapper<Staff>();
		queryWrapper.eq("sid", sid);
		Staff staff = staffService.getOne(queryWrapper);
		List<Staff> staffs = new ArrayList<Staff>();
		staffs.add(staff);
		String str = new Gson().toJson(staffs);
		return new Gson().toJson(staffs);
	}
}

